package com.example.huixue.controller;

import com.example.huixue.common.Result;
import com.example.huixue.dto.AdminInfoResponse;
import com.example.huixue.dto.InitAdminRequest;
import com.example.huixue.service.AdminService;
import com.example.huixue.service.UserService;
import com.example.huixue.service.ResourceService;
import com.example.huixue.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "*")
public class AdminController {

    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private AdminService adminService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private ResourceService resourceService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 验证管理员token
     */
    private Integer validateAdminToken(String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            throw new RuntimeException("未提供有效的认证令牌");
        }
        
        String jwtToken = token.substring(7);
        
        if (!jwtUtil.validateToken(jwtToken)) {
            throw new RuntimeException("token已过期或无效，请重新登录");
        }
        
        // 检查是否为管理员token
        String role = jwtUtil.getRoleFromToken(jwtToken);
        String userType = jwtUtil.getUserTypeFromToken(jwtToken);
        
        if (!"ADMIN".equals(role) || !"admin".equals(userType)) {
            throw new RuntimeException("无权限访问，请使用管理员账户登录");
        }
        
        return jwtUtil.getUserIdFromToken(jwtToken);
    }

    /**
     * 检查是否已有管理员账户
     */
    @PostMapping("/check-admin")
    public Result<Boolean> checkAdmin() {
        try {
            boolean hasAdmin = adminService.hasAdmin();
            return Result.success("检查管理员状态成功", hasAdmin);
        } catch (Exception e) {
            logger.error("检查管理员状态失败", e);
            return Result.error("检查管理员状态失败：" + e.getMessage());
        }
    }

    /**
     * 初始化管理员账户（仅在没有管理员时可用）
     */
    @PostMapping("/init")
    public Result<?> initAdmin(@RequestBody InitAdminRequest request) {
        try {
            logger.info("收到初始化管理员请求: {}", request.getUsername());
            
            // 检查是否已存在管理员
            if (adminService.hasAdmin()) {
                logger.warn("管理员账户已存在，初始化请求被拒绝");
                return Result.error("管理员账户已存在");
            }
            
            // 创建管理员账户
            AdminInfoResponse admin = adminService.createAdmin(
                request.getUsername(), 
                request.getEmail(), 
                request.getPassword()
            );
            
            logger.info("管理员账户创建成功: {}", admin.getUsername());
            return Result.success("管理员账户创建成功", admin);
        } catch (Exception e) {
            logger.error("创建管理员账户失败", e);
            return Result.error("创建管理员账户失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员登录
     */
    @PostMapping("/admin-login")
    public Result<?> adminLogin(@RequestBody Map<String, String> loginData) {
        try {
            String username = loginData.get("username");
            String password = loginData.get("password");
            
            if (username == null || username.trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }
            
            if (password == null || password.trim().isEmpty()) {
                return Result.error("密码不能为空");
            }
            
            AdminInfoResponse admin = adminService.login(username.trim(), password);
            
            return Result.success("登录成功", admin);
        } catch (Exception e) {
            logger.error("管理员登录失败", e);
            return Result.error("登录失败：" + e.getMessage());
        }
    }
    
    /**
     * 验证管理员token有效性
     */
    @PostMapping("/validate-token")
    public Result<AdminInfoResponse> validateToken(@RequestHeader("Authorization") String token) {
        try {
            Integer adminId = validateAdminToken(token);
            
            // 获取管理员信息
            AdminInfoResponse adminInfo = adminService.getAdminById(adminId);
            
            return Result.success("token验证成功", adminInfo);
        } catch (Exception e) {
            logger.error("管理员token验证失败", e);
            return Result.error("token验证失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员退出登录
     */
    @PostMapping("/admin-logout")
    public Result<String> adminLogout(@RequestHeader("Authorization") String token) {
        try {
            // 验证token有效性
            validateAdminToken(token);
            
            // 这里可以添加token黑名单逻辑
            logger.info("管理员退出登录成功");
            return Result.success("退出登录成功");
        } catch (Exception e) {
            logger.error("管理员退出登录失败", e);
            return Result.error("退出登录失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取系统统计数据
     */
    @GetMapping("/stats")
    public Result<?> getStats() {
        try {
            logger.info("获取系统统计数据");
            
            // 获取各种统计数据
            Map<String, Object> stats = new HashMap<>();
            
            // 用户统计
            long totalUsers = userService.getTotalUserCount();
            long todayNewUsers = userService.getTodayNewUserCount();
            long activeUsers = userService.getActiveUserCount();
            long adminUsers = userService.getAdminUserCount();
            
            // 资源统计 - 使用真实数据
            Map<String, Object> resourceStats = resourceService.getResourceStats();
            long totalResources = (Long) resourceStats.getOrDefault("total", 0L);
            long approvedResources = (Long) resourceStats.getOrDefault("approved", 0L);
            long pendingResources = (Long) resourceStats.getOrDefault("pending", 0L);
            long totalDownloads = (Long) resourceStats.getOrDefault("totalDownloads", 0L);
            
            // 学习小组统计 - 使用真实数据
            // 这里需要注入StudyGroupService来获取真实数据
            long totalGroups = 0;
            long activeGroups = 0;
            
            stats.put("users", Map.of(
                "total", totalUsers,
                "todayNew", todayNewUsers, 
                "active", activeUsers,
                "admin", adminUsers
            ));
            
            stats.put("resources", Map.of(
                "total", totalResources,
                "approved", approvedResources,
                "pending", pendingResources,
                "totalDownloads", totalDownloads
            ));
            
            stats.put("groups", Map.of(
                "total", totalGroups,
                "active", activeGroups
            ));
            
            // 今日数据
            stats.put("today", Map.of(
                "newUsers", todayNewUsers,
                "newResources", 8,
                "downloads", 256,
                "newGroups", 3
            ));
            
            return Result.success("统计数据获取成功", stats);
        } catch (Exception e) {
            logger.error("获取统计数据失败", e);
            return Result.error("获取统计数据失败：" + e.getMessage());
        }
    }
} 